package systemMethods;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.OutputKeys;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xpk
 * Date: 11/11/13
 * Time: 8:54 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestingSystemUtils {

    public static void getOutFromProgram(String finalMessage, int finalCode) {
        System.out.println(finalMessage);
        System.exit(finalCode);
    }

    public static List<String> readFile(String fileName) {
        BufferedReader contentOfFile = null;
        String lineOfFile;
        ArrayList<String> linesOfFileCollection = new ArrayList<String>();

        try {
            contentOfFile = new BufferedReader(new FileReader(fileName));
            while (((lineOfFile = contentOfFile.readLine()) != null)) {
                linesOfFileCollection.add(lineOfFile);
            }
        } catch (FileNotFoundException e) {
            getOutFromProgram(e.getMessage(), -1);
        } catch (IOException e) {
            getOutFromProgram(e.getMessage(), -1);
        } finally {
            try {
                contentOfFile.close();
            } catch (IOException e) {
                getOutFromProgram("IO error from the file : " + fileName, -1);
            }
        }
        return linesOfFileCollection;
    }

    public static String readFromConsole() {
        BufferedReader input;
        input = new BufferedReader(new InputStreamReader(System.in));
        try {
            return input.readLine();
        } catch (IOException e) {
            getOutFromProgram(e.getMessage(), -1);
            return null;
        }
    }

    public static String doXSLT(String xslFileName, String xmlFileName) {
        String stringOfQuestionsAndAnswers = "";
        StringWriter stringWriter = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        StreamSource xslStream = new StreamSource(xslFileName);
        StreamSource xmlStream = new StreamSource(xmlFileName);
        StreamResult streamResult = new StreamResult(stringWriter);

        try {
            Transformer transformer = transformerFactory.newTransformer(xslStream);
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(xmlStream, streamResult);
            stringOfQuestionsAndAnswers = stringWriter.toString();
        } catch (TransformerException e) {
            getOutFromProgram(e.getMessage(), -1);
        }

        return stringOfQuestionsAndAnswers;
    }
}
